<template>
  <div class="task-list-container">
    <div class="header">
      <h2>任务列表</h2>
      <button class="add-btn" @click="showAddForm = true">新增任务</button>
    </div>

    <!-- 搜索表单 -->
    <div class="search-form">
      <div class="search-group">
        <input type="text" v-model="searchForm.task_id" placeholder="任务ID" @input="handleSearch">
        <input type="text" v-model="searchForm.task_name" placeholder="任务名称" @input="handleSearch">
        <input type="text" v-model="searchForm.live_room_id" placeholder="直播间号" @input="handleSearch">
        <input type="date" v-model="searchForm.date" @input="handleSearch">
        <input type="text" v-model="searchForm.task_nature" placeholder="任务性质" @input="handleSearch">
        <input type="text" v-model="searchForm.task_source" placeholder="任务来源" @input="handleSearch">
        <input type="text" v-model="searchForm.task_priority" placeholder="任务等级" @input="handleSearch">
        <button class="clear-btn" @click="clearSearch">清空</button>
      </div>
    </div>

    <!-- 新增任务表单对话框 -->
    <div v-if="showAddForm" class="modal-overlay">
      <div class="modal-content">
        <h3>新增任务</h3>
        <form @submit.prevent="handleAddTask" class="add-form">
          <div class="form-group">
            <label for="task_id">任务ID</label>
            <input type="text" id="task_id" v-model="newTask.task_id" />
          </div>
          <div class="form-group">
            <label for="task_name">任务名称</label>
            <input type="text" id="task_name" v-model="newTask.task_name" required />
          </div>
          <div class="form-group">
            <label for="live_room_id">直播间</label>
            <input type="text" id="live_room_id" v-model="newTask.live_room_id" />
          </div>
          <div class="form-group">
            <label for="date">日期</label>
            <input type="date" id="date" v-model="newTask.date" required />
          </div>
          <div class="form-group">
            <label for="start_time">开始时间</label>
            <input type="time" id="start_time" v-model="newTask.start_time" />
          </div>
          <div class="form-group">
            <label for="end_time">结束时间</label>
            <input type="time" id="end_time" v-model="newTask.end_time" />
          </div>
          <div class="form-group">
            <label for="task_nature">任务性质</label>
            <input type="text" id="task_nature" v-model="newTask.task_nature" />
          </div>
          <div class="form-group">
            <label for="task_source">任务来源</label>
            <input type="text" id="task_source" v-model="newTask.task_source" />
          </div>
          <div class="form-group">
            <label for="task_priority">任务等级</label>
            <input type="text" id="task_priority" v-model="newTask.task_priority" />
          </div>
          <div class="form-actions">
            <button type="submit" :disabled="isSubmitting">
              {{ isSubmitting ? '提交中...' : '提交' }}
            </button>
            <button type="button" class="cancel-btn" @click="showAddForm = false">取消</button>
          </div>
        </form>
      </div>
    </div>

    <div class="table-container">
      <table v-if="tasks.length > 0">
        <thead>
          <tr>
            <th v-if="isAdmin">上传者</th>
            <th>任务ID</th>
            <th>任务名称</th>
            <th>直播间</th>
            <th>日期</th>
            <th>开始时间</th>
            <th>结束时间</th>
            <th>任务性质</th>
            <th>任务来源</th>
            <th>任务等级</th>
            <th>创建时间</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="task in tasks" :key="task.id">
            <td v-if="isAdmin">{{ task.username }}</td>
            <td>
              <input v-if="editingId === task.id" v-model="editingTask.task_id" type="text">
              <span v-else>{{ task.task_id }}</span>
            </td>
            <td>
              <input v-if="editingId === task.id" v-model="editingTask.task_name" type="text" required>
              <span v-else>{{ task.task_name }}</span>
            </td>
            <td>
              <input v-if="editingId === task.id" v-model="editingTask.live_room_id" type="text">
              <span v-else>{{ task.live_room_id }}</span>
            </td>
            <td>
              <input v-if="editingId === task.id" v-model="editingTask.date" type="date" required>
              <span v-else>{{ formatDate(task.date) }}</span>
            </td>
            <td>
              <input v-if="editingId === task.id" v-model="editingTask.start_time" type="time">
              <span v-else>{{ task.start_time }}</span>
            </td>
            <td>
              <input v-if="editingId === task.id" v-model="editingTask.end_time" type="time">
              <span v-else>{{ task.end_time }}</span>
            </td>
            <td>
              <input v-if="editingId === task.id" v-model="editingTask.task_nature" type="text">
              <span v-else>{{ task.task_nature }}</span>
            </td>
            <td>
              <input v-if="editingId === task.id" v-model="editingTask.task_source" type="text">
              <span v-else>{{ task.task_source }}</span>
            </td>
            <td>
              <input v-if="editingId === task.id" v-model="editingTask.task_priority" type="text">
              <span v-else>{{ task.task_priority }}</span>
            </td>
            <td>{{ formatDateTime(task.created_at) }}</td>
            <td class="actions">
              <template v-if="editingId === task.id">
                <button class="save-btn" @click="handleSave(task.id)">保存</button>
                <button class="cancel-btn" @click="cancelEdit">取消</button>
              </template>
              <template v-else>
                <button class="edit-btn" @click="startEdit(task)">修改</button>
                <button class="delete-btn" @click="handleDelete(task.id)">删除</button>
              </template>
            </td>
          </tr>
        </tbody>
      </table>
      <div v-else class="no-data">暂无数据</div>
    </div>

    <!-- 分页控件 -->
    <div class="pagination" v-if="pagination.total > 0">
      <button 
        :disabled="pagination.current === 1" 
        @click="changePage(pagination.current - 1)"
      >
        上一页
      </button>
      <span class="page-info">
        第 {{ pagination.current }} 页 / 共 {{ pagination.totalPages }} 页
      </span>
      <button 
        :disabled="!pagination.hasMore" 
        @click="changePage(pagination.current + 1)"
      >
        下一页
      </button>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import request from '../utils/request'
import config from '../config'

const router = useRouter()
const tasks = ref([])
const isAdmin = ref(false)
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const filters = ref({
  task_id: '',
  task_name: '',
  live_room_id: '',
  date: '',
  task_nature: '',
  task_source: '',
  task_priority: ''
})
const pagination = ref({
  current: 1,
  pageSize: 10,
  total: 0,
  totalPages: 0,
  hasMore: false
})

const formatDate = (dateStr) => {
  if (!dateStr) return '';
  return dateStr.split('T')[0];
}

const formatDateTime = (dateStr) => {
  if (!dateStr) return '';
  const date = new Date(dateStr);
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  });
}

const searchForm = ref({
  task_id: '',
  task_name: '',
  live_room_id: '',
  date: '',
  task_nature: '',
  task_source: '',
  task_priority: ''
})

// 使用防抖函数优化搜索
const debounce = (fn, delay) => {
  let timer = null
  return function (...args) {
    if (timer) clearTimeout(timer)
    timer = setTimeout(() => fn.apply(this, args), delay)
  }
}

const handleSearch = debounce(() => {
  fetchTasks(1) // 搜索时重置到第一页
}, 300)

const clearSearch = () => {
  searchForm.value = {
    task_id: '',
    task_name: '',
    live_room_id: '',
    date: '',
    task_nature: '',
    task_source: '',
    task_priority: ''
  }
  fetchTasks(1)
}

const fetchTasks = async () => {
  try {
    loading.value = true
    const response = await request.get(config.endpoints.tasks, {
      params: {
        page: pagination.value.current,
        pageSize: pagination.value.pageSize,
        ...searchForm.value
      }
    })

    tasks.value = response.data.data
    pagination.value = response.data.pagination
    pagination.value = {
      ...pagination.value,
      hasMore: pagination.value.current < pagination.value.totalPages
    }

    // 获取用户角色
    const user = JSON.parse(localStorage.getItem('user'))
    isAdmin.value = user?.role >= 10
  } catch (error) {
    console.error('获取任务列表失败:', error)
  } finally {
    loading.value = false
  }
}

const changePage = (page) => {
  pagination.value.current = page
  fetchTasks(page)
}

const showAddForm = ref(false)
const isSubmitting = ref(false)
const newTask = ref({
  task_id: '',
  task_name: '',
  live_room_id: '',
  date: '',
  start_time: '',
  end_time: '',
  task_nature: '',
  task_source: '',
  task_priority: ''
})

const handleAddTask = async () => {
  isSubmitting.value = true
  try {
    await request.post(config.endpoints.tasks, newTask.value)
    
    // 重新加载任务列表
    await fetchTasks()
    
    // 关闭表单并重置
    showAddForm.value = false
    newTask.value = {
      task_id: '',
      task_name: '',
      live_room_id: '',
      date: '',
      start_time: '',
      end_time: '',
      task_nature: '',
      task_source: '',
      task_priority: ''
    }
  } catch (error) {
    console.error('添加任务失败:', error)
    alert(error.response?.data?.error || '添加任务失败')
  } finally {
    isSubmitting.value = false
  }
}

const handleDelete = async (id) => {
  if (!confirm('确定要删除这条记录吗？')) {
    return
  }

  try {
    await request.delete(`${config.endpoints.tasks}/${id}`)
    alert('删除成功')
    fetchTasks()
  } catch (error) {
    console.error('删除任务失败:', error)
    alert(error.response?.data?.error || '删除失败')
  }
}

const editingId = ref(null)
const editingTask = ref({})

const startEdit = (task) => {
  editingId.value = task.id
  editingTask.value = { ...task }
}

const cancelEdit = () => {
  editingId.value = null
  editingTask.value = {}
}

const handleSave = async (id) => {
  try {
    await request.put(`${config.endpoints.tasks}/${id}`, editingTask.value)

    // 重新加载任务列表
    await fetchTasks()
    
    // 退出编辑模式
    editingId.value = null
    editingTask.value = {}
  } catch (error) {
    console.error('更新任务失败:', error)
    alert(error.response?.data?.error || '更新失败')
  }
}

onMounted(() => {
  fetchTasks()
})
</script>

<style scoped>
.task-list-container {
  padding: 10px 20px;
}

.table-container {
  overflow-x: auto;
  margin: 10px 0;
  max-width: 100%;
}

table {
  width: 100%;
  border-collapse: collapse;
  min-width: 1200px;
}

th, td {
  padding: 8px 6px;
  text-align: left;
  border-bottom: 1px solid #ddd;
  box-sizing: border-box;
  height: 41px;
}

th {
  background-color: #f5f5f5;
  font-weight: bold;
}

tr:hover {
  background-color: #f9f9f9;
}

.no-data {
  text-align: center;
  padding: 20px;
  color: #666;
}

.pagination {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 20px;
  margin-top: 20px;
}

button {
  padding: 8px 16px;
  background-color: #4CAF50;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

button:disabled {
  background-color: #cccccc;
  cursor: not-allowed;
}

.page-info {
  color: #666;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.add-btn {
  background-color: #4CAF50;
  color: white;
  padding: 8px 16px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.modal-content {
  background-color: white;
  padding: 20px;
  border-radius: 8px;
  max-width: 500px;
  width: 90%;
  max-height: 90vh;
  overflow-y: auto;
}

.add-form {
  display: grid;
  gap: 15px;
}

.form-group {
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.form-actions {
  display: flex;
  gap: 10px;
  justify-content: flex-end;
  margin-top: 20px;
}

.cancel-btn {
  background-color: #6c757d;
}

input {
  padding: 8px;
  border: 1px solid #ddd;
  border-radius: 4px;
}

.actions {
  white-space: nowrap;
  display: flex;
  gap: 4px;
  justify-content: flex-end;
  align-items: center;
  min-width: 110px;
}

.delete-btn {
  padding: 4px 8px;
  background-color: #dc3545;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 11px;
  min-width: 48px;
}

.delete-btn:hover {
  background-color: #c82333;
}

.edit-btn {
  padding: 4px 8px;
  background-color: #ffc107;
  color: black;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 11px;
  min-width: 48px;
}

.edit-btn:hover {
  background-color: #e0a800;
}

.save-btn {
  padding: 4px 8px;
  background-color: #28a745;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 11px;
  min-width: 48px;
}

.save-btn:hover {
  background-color: #218838;
}

td input {
  width: 100%;
  padding: 4px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
}

.search-form {
  margin: 10px 0;
  padding: 15px;
  background-color: #f8f9fa;
  border-radius: 8px;
}

.search-group {
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
}

.search-group input {
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  flex: 1;
  min-width: 150px;
}

.clear-btn {
  padding: 8px 16px;
  background-color: #6c757d;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.clear-btn:hover {
  background-color: #5a6268;
}

/* 管理员视图的列宽 */
.task-list-container:has(th:first-child:contains('上传者')) {
  & th:nth-child(1), & td:nth-child(1) { width: 8%; }    /* 上传者 */
  & th:nth-child(2), & td:nth-child(2) { width: 8%; }    /* 任务ID */
  & th:nth-child(3), & td:nth-child(3) { width: 35%; }   /* 任务名称 */
  & th:nth-child(4), & td:nth-child(4) { width: 6%; }    /* 直播间 */
  & th:nth-child(5), & td:nth-child(5) { width: 7%; }    /* 日期 */
  & th:nth-child(6), & td:nth-child(6) { width: 5%; }    /* 开始时间 */
  & th:nth-child(7), & td:nth-child(7) { width: 5%; }    /* 结束时间 */
  & th:nth-child(8), & td:nth-child(8) { width: 6%; }    /* 任务性质 */
  & th:nth-child(9), & td:nth-child(9) { width: 6%; }    /* 任务来源 */
  & th:nth-child(10), & td:nth-child(10) { width: 4%; }  /* 任务等级 */
  & th:nth-child(11), & td:nth-child(11) { width: 8%; }  /* 创建时间 */
  & th:last-child, & td:last-child { width: 110px; }
}

/* 普通用户视图的列宽 */
.task-list-container:not(:has(th:first-child:contains('上传者'))) {
  & th:nth-child(1), & td:nth-child(1) { width: 8%; }    /* 任务ID */
  & th:nth-child(2), & td:nth-child(2) { width: 35%; }   /* 任务名称 */
  & th:nth-child(3), & td:nth-child(3) { width: 6%; }    /* 直播间 */
  & th:nth-child(4), & td:nth-child(4) { width: 7%; }    /* 日期 */
  & th:nth-child(5), & td:nth-child(5) { width: 5%; }    /* 开始时间 */
  & th:nth-child(6), & td:nth-child(6) { width: 5%; }    /* 结束时间 */
  & th:nth-child(7), & td:nth-child(7) { width: 6%; }    /* 任务性质 */
  & th:nth-child(8), & td:nth-child(8) { width: 6%; }    /* 任务来源 */
  & th:nth-child(9), & td:nth-child(9) { width: 4%; }    /* 任务等级 */
  & th:nth-child(10), & td:nth-child(10) { width: 8%; }  /* 创建时间 */
  & th:last-child, & td:last-child { width: 110px; }
}

/* 所有单元格的基本文本处理 */
td {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

/* 任务名称列的文本处理 */
td:nth-child(2):has(~ td:last-child),  /* 普通用户视图 */
td:nth-child(3):has(~ td:last-child) { /* 管理员视图 */
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

/* 任务名称列的悬停效果 */
td:nth-child(2):has(~ td:last-child):hover,  /* 普通用户视图 */
td:nth-child(3):has(~ td:last-child):hover { /* 管理员视图 */
  overflow: visible;
  white-space: normal;
  background-color: #fff;
  position: relative;
  z-index: 1;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}

.edit-btn, .delete-btn, .save-btn, .cancel-btn {
  padding: 4px 8px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 11px;
  width: 48px;
}

/* 操作列的样式 */
td.actions {
  height: 41px;
  padding: 0 4px;
  vertical-align: middle;
}

.actions {
  white-space: nowrap;
  display: flex;
  justify-content: space-between;
  align-items: center;
  min-width: 110px;
  width: 100%;
}

/* 编辑状态下的按钮组样式 */
td.actions template {
  display: flex;
  width: 100%;
  justify-content: space-between;
}
</style> 